# coding: utf-8

import tornado
import json
import math
import datetime
from bson import ObjectId
from handlers.base import BaseHandler

class BmisHandler(BaseHandler):
    @tornado.gen.coroutine
    def get(self):
        try:
            rid = self.get_query_argument('rid')
        except Exception as err:
            self.response_msg(400, '参数错误')
            return
        #判断page是否存在
        skip = 0
        limit = 7
        results = []
        try:
            if 'page' in self.request.arguments:
                page = self.get_argument('page')
                if not page:
                    page = 1
                #返回对应page的list
                limit = 20
                skip = (int(page)-1)*limit
            #下面就是查询语句
            where = {}
            where['role'] = rid
            where['measureType'] = 'bmi'
            #限制返回字段
            fieldList = {}
            fieldList['_id'] = 1
            fieldList['bmiHeight'] = 1
            fieldList['bmiValue'] = 1
            fieldList['bmiWeight'] = 1
            fieldList['created_at'] = 1
            fieldList['advice'] = 1
            #组装语句
            listRes = self.db.HMMeasure.find(where,fieldList).sort('created_at',-1).skip(skip).limit(limit)
            while(yield listRes.fetch_next):
                tempObj = listRes.next_object()
                tempObj['objectId'] = str(tempObj['_id'])
                tempObj['created_at'] = tempObj['created_at'].strftime("%Y-%m-%d %H:%M")
                del tempObj['_id']
                #获取建议
                if 'page' in self.request.arguments:
                    advice = yield self.db.HMMeasureAdvice.find_one({'_id': ObjectId(tempObj['advice'])})
                    tempObj['adviceStr'] = advice['diet']
                results.append(tempObj)
            self.response_msg(200,"获取成功",results)
        except Exception as e:
            print(e)
            self.response_msg(500,str(e))


    @tornado.gen.coroutine
    def post(self):
        try:
            bmiHeight = self.get_argument('bmiHeight')
            bmiWeight = self.get_argument('bmiWeight')
            rid = self.get_argument('rid')
            created_at = self.get_argument('created_at')
            created_at = datetime.datetime.strptime(created_at, '%Y-%m-%dT%H:%M:%S')
        except Exception as err:
            print(err)
            self.response_msg(400, '参数错误')
            return
        bmi = float(bmiWeight)*10000/(float(bmiHeight)*float(bmiHeight))
        bmi = round(bmi, 2)

        if bmi < 18.5:
            tag = 'BMI低'
        elif bmi >= 18.5 and bmi <= 24.99:
            tag = 'BMI正常'
        elif bmi > 24.99 and bmi < 28:
            tag = 'BMI高'
        else:
            tag = 'BMI肥胖'

        advice = yield self.db.HMMeasureAdvice.find_one({'tag': tag})
        ret = yield self.db.HMMeasure.save({'role': rid, 'bmiHeight': bmiHeight, 'bmiWeight': bmiWeight, 'measureType': 'bmi',
                                            'bmiValue': bmi, 'created_at': created_at, 'advice': str(advice['_id'])
                                            })
        self.response_msg(200, '保存成功', {'objectId': str(ret)})
